package com.ljsw.activity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ljsw.application.App;
import com.ljsw.dialog.LoginDialog;
import com.ljsw.dialog.TimeOut;
import com.ljsw.entity.User;
import com.ljsw.server.UpServer;
import com.ljsw.url.ServerUrl;
import com.ljsw.util.DialogManager;
import com.ljsw.util.Screen;
import com.ljsw.util.Skip;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 主界面--用户登录
 * 作者: 石锚
 * 版本: 1.0
 * 日期: 2015-10-8
 *
 *
 * 修改于1.29    最贴近上线版本
 */
public class LoginActivity extends Activity implements OnClickListener {
    private App app; //全局变量
    private DialogManager dmanager;//弹出框管理类
    private Map<Integer, EditText> editLayout = new HashMap<Integer, EditText>();
    private Map<Integer, TextView> textLayout = new HashMap<Integer, TextView>();
    private LoginDialog dialog;//登录框
    private TextView login;//登录
    private EditText name,//用户名
            pwd;//密码
    private TextView imageshezhi;
    private Handler handler;
    private TimeOut timeout;//超时连接
    private String username;//用户名
    private String userpwd;//用户密码
    private User user;//用户
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        setContentView(R.layout.activity_main);
        app = (App) getApplication();//映射全局变量
        dmanager = new DialogManager(this);

        // 数据初始化获取屏幕分辨率，从而计算出缩放比例
        Screen.getDisplay(this);
        //启动activity时不自动弹出软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        dialog = dmanager.getLoginDialog();
        timeout = dmanager.getTimeOut();//超时弹框
        initView();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                dialog.dismiss();
                switch (msg.what) {
                    case 0://登录成功后跳转 上门服务页面
                        app.user = user;
                        Log.d("login用户role------------",user.getUserId());
                        app.userZhanghao = username;

                        Skip.skip(LoginActivity.this, SmfwMainActivity.class, null, 0);
                        break;
                    case 1://登录超时
                        Toast.makeText(LoginActivity.this, "正在登陆请检查网络" + App.getApp().fanhuiMsg, Toast.LENGTH_SHORT).show();
                        timeout.show();
                        queding();
                        break;
                    case 2://用户不存在
                        quxiao();
                        Toast.makeText(LoginActivity.this, "超时" + App.getApp().fanhuiMsg, Toast.LENGTH_SHORT).show();
                        break;
                    case 3://异常加载，无法访问服务器
                        Toast.makeText(LoginActivity.this, "" + "加载异常" + App.getApp().fanhuiMsg, Toast.LENGTH_SHORT).show();
                        timeout.show();
                        timeout.setTitle("加载异常");
                        queding();
                        quxiao();
                        break;
                    case 4://账户长度是否正确符合要求 用户不存在
                        Toast.makeText(LoginActivity.this, "账户长度不对", Toast.LENGTH_SHORT).show();
                        break;
                    case 5://判断密码的长度密码错误
                        Toast.makeText(LoginActivity.this, "请检查密码", Toast.LENGTH_SHORT).show();
                        break;

                    case 7://用户不正确
                        Toast.makeText(LoginActivity.this, "请检查用户名", Toast.LENGTH_SHORT).show();
                        break;

                    default:
                        Toast.makeText(LoginActivity.this, "请检查网络服务", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
    }

    /**
     * 初始化控件
     */
    public void initView() {
        imageshezhi = (TextView) this.findViewById(R.id.image_shezhi);
        login = (TextView) this.findViewById(R.id.login);//登录按钮
        name = (EditText) this.findViewById(R.id.name);//用户名输入
        pwd = (EditText) this.findViewById(R.id.pwd);//密码输入
        textLayout.put(R.id.login, login);
        editLayout.put(R.id.name, name);
        editLayout.put(R.id.pwd, pwd);
        Screen.changeEditViewSize(editLayout, this);
        Screen.changeTextViewSize(textLayout, this);
        login.setOnClickListener(this);//触摸事件
        imageshezhi.setOnClickListener(this);
        Screen.getDisplay(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        boolean  text_namesprecethree=fileIsExists("text_namesprecethree.txt");
        boolean   text_urlthree=fileIsExists("text_url.txt");
        boolean txt_namespace = fileIsExists("namespace.txt");
        boolean txt_url = fileIsExists("url.txt");
        if (txt_url == true && txt_namespace == true) {
            inputSDCardNAMESPACE();
            inputSDCardURL();
        } else {

        }





        if (text_namesprecethree == true && text_urlthree == true) {
            inputSDCardNAMESPACEthree();
            inputSDCardURLthree();
        } else {

        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    /**
     * 登录
     */
    public void login() {
//        Skip.skip(LoginActivity.this, SmfwMainActivity.class, null, 0);
        dialog.show();
        username = name.getText().toString();
        userpwd = pwd.getText().toString();
        new Thread(new Runnable() {
                public void run() {
                try {
                    if (username.length() == 0 || username.length() >= 9) {
                        handler.sendEmptyMessage(4);//查无此人信息
                    } else if (userpwd.length() == 0 || userpwd.length() >= 30) {
                        handler.sendEmptyMessage(5);//查无此人信息
                    } else if (isNumeric(username) == true) {
                        user = UpServer.login(username, userpwd);
                        if (user != null) {
                            handler.sendEmptyMessage(0);//验证成功 返回三个元素在user
                        } else {
                            handler.sendEmptyMessage(2);//查无此人信息
                        }
                    } else {
                        handler.sendEmptyMessage(7);//不是数字 handler.sendEmptyMessage(6);//不是数字
                    }
                } catch (SocketTimeoutException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(1);//超时链接
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(6);//查无此人信息
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(6);//不是数字
                } catch (Exception e) {

                    e.printStackTrace();
                    Log.e("b","异常"+e);
                    handler.sendEmptyMessage(6);//不是数字
                }


            }
        }).start();
    }

    /**
     * 确定点击事件
     */
    public void queding() {
        timeout.setQueDing("确定", new OnClickListener() {
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                login();
            }
        });
    }

    /**
     * 取消点击事件
     */
    public void quxiao() {
        timeout.setQueXiao("取消", new OnClickListener() {
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
            }
        });
    }

    /**
     * 本机读取保存的地址 文件名 需要赋值的控件
     */
    public void inputSDCardNAMESPACE() {
        try {
            System.out.println("-----读取文件-----");
            File file = new File(Environment.getExternalStorageDirectory(),
                    "namespace.txt");
            BufferedReader br = new BufferedReader(new FileReader(file));
            String readline = "";
            StringBuffer sb = new StringBuffer();
            while ((readline = br.readLine()) != null) {
                sb.append(readline);
            }
            String getsaveinfo = sb.toString();
            System.out.println("=====读取:" + getsaveinfo);
            if (!"".equals(getsaveinfo)) {
                ServerUrl.NAMESPACE = getsaveinfo;
            }

            System.out.println("命名空间：" + ServerUrl.NAMESPACE);
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void inputSDCardURL() {
        try {
            System.out.println("-----读取文件-----");
            File file = new File(Environment.getExternalStorageDirectory(),
                    "url.txt");
            BufferedReader br = new BufferedReader(new FileReader(file));
            String readline = "";
            StringBuffer sb = new StringBuffer();
            while ((readline = br.readLine()) != null) {
                sb.append(readline);
            }
            String getsaveinfo = sb.toString();
            if (!"".equals(getsaveinfo)) {
                ServerUrl.URL = getsaveinfo + "/cash_pda";
                ServerUrl.URL1 = getsaveinfo + "/cash_up";
                ServerUrl.URL2 = getsaveinfo + "/cash_cm";
            }
            System.out.println("地址：" + getsaveinfo);

            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void inputSDCardNAMESPACEthree() {
        try {
            System.out.println("-----读取文件-----");
            File file = new File(Environment.getExternalStorageDirectory(),
                    "text_namesprecethree.txt");
            BufferedReader br = new BufferedReader(new FileReader(file));
            String readline = "";
            StringBuffer sb = new StringBuffer();
            while ((readline = br.readLine()) != null) {
                sb.append(readline);
            }
            String getsaveinfo = sb.toString();
            System.out.println("=====读取:" + getsaveinfo);
            if (!"".equals(getsaveinfo)) {
                ServerUrl.NAMESPACEseven = getsaveinfo;
            }

            System.out.println("命名空间：" + ServerUrl.NAMESPACEseven);
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void inputSDCardURLthree() {
        try {
            System.out.println("-----读取文件-----");
            File file = new File(Environment.getExternalStorageDirectory(),
                    "text_url.txt");
            BufferedReader br = new BufferedReader(new FileReader(file));
            String readline = "";
            StringBuffer sb = new StringBuffer();
            while ((readline = br.readLine()) != null) {
                sb.append(readline);
            }
            String getsaveinfo = sb.toString();
            if (!"".equals(getsaveinfo)) {
//                ServerUrl.URL = getsaveinfo + "/cash_pda";
//                ServerUrl.URL1 = getsaveinfo + "/cash_up";
//                ServerUrl.URL2 = getsaveinfo + "/cash_cm";
                ServerUrl.URL21=getsaveinfo+"/checkInventory";
                ServerUrl.URL20=getsaveinfo+"/scutcheon";
            }
            System.out.println("地址：" + getsaveinfo);

            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean fileIsExists(String textname) {
        try {
            File f = new File(Environment.getExternalStorageDirectory()
                    .getPath() + "/" + textname);
            if (!f.exists()) {
                System.out.println("-----文件不存在-----");
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        System.out.println("-----文件存在-----");
        return true;
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.login:
                login();//调用登录的方法接口
                break;

            case R.id.image_shezhi:
                Skip.skip(LoginActivity.this, SystemSetActivity.class, null, 0);
                break;
        }
    }

    public boolean isNumeric(String username) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(username);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
}
